#include "DisplayTagEditor.h"
#include "ui_DisplayTagEditor.h"
#include <QPainter>
#include <QGraphicsPixmapItem>
#include <QFileDialog>
#include "swf/SWFTagWrapper.h"
#include "swf/utils/ImageHelper.h"
#include "swf/SWF.h"
#include "swf/SWFEncoder.h"

DisplayTagEditor::DisplayTagEditor(SWFTagWrapper* tag, QWidget *parent)
	: QWidget(parent)
	, ui(new Ui::DisplayTagEditor)
	, _wrapper(tag)
{
	_bits = dynamic_cast<DefineTag*>(_wrapper->getTag());
	assert(_bits);

    ui->setupUi(this);

	SWF* swf = this->createSWF();

	QTemporaryFile tempFile;
	tempFile.open();
	QFileInfo tempFileInfo(tempFile);
	tempFile.remove();

	SWFEncoder encoder;
	encoder.save(swf, tempFileInfo.absoluteFilePath().toStdString());

	ui->flashWidget->setControl(QString::fromUtf8("{d27cdb6e-ae6d-11cf-96b8-444553540000}"));
	ui->flashWidget->dynamicCall("LoadMovie(long,string)", 0, tempFileInfo.absoluteFilePath());
	//ui->flashWidget->dynamicCall("WMode", "transparent");
	ui->flashWidget->dynamicCall("Scale", "noscale");
}

DisplayTagEditor::~DisplayTagEditor()
{
    delete ui;
}

void DisplayTagEditor::onReplace()
{
}

void DisplayTagEditor::onExport()
{
	QString filePath = QFileDialog::getSaveFileName(this, "Save SWF", this->getEditorName(), "SWF(*.swf)");
	if (filePath.length() > 0)
	{
		SWFEncoder encoder;
		encoder.save(this->createSWF(), filePath.toStdString());
	}
}

const QString DisplayTagEditor::getEditorName() const 
{
	return QString("Display %1").arg(_bits->characterID);
}

QWidget* DisplayTagEditor::asWidget() const 
{
	return (QWidget*) this;
}

SWF* DisplayTagEditor::createSWF()
{
	SWF* swf = SWF::create();

	SWFTagRef* refen = SWFTagRef::create(_bits);

	SWFFrame* frame = SWFFrame::create();
	TagPlaceObject2* placeObject2 = TagPlaceObject2::create();
	placeObject2->code = PlaceObject2;
	placeObject2->putReference(refen);
	placeObject2->setCharacter(refen);

	DisplayTag* shape = dynamic_cast<DisplayTag*>(_bits);
	if (shape)
	{
		placeObject2->flags1 |= HAS_MATRIX;
		Rect bounds = shape->getBounds();
		swf->width = (bounds.Xmax - bounds.Xmin) / 20;
		swf->height = (bounds.Ymax - bounds.Ymin) / 20;
		placeObject2->matrix.TranslateX = -bounds.Xmin;
		placeObject2->matrix.TranslateY = -bounds.Ymin;
		placeObject2->matrix.NTranslateBits = 15;
	}

	frame->addControlTag(placeObject2);
	swf->addFrame(frame);
	return swf;
}
